package com.br.egaragens.activitys;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.br.egaragens.R;
import com.br.egaragens.controles.EmpresasController;
import com.br.egaragens.controles.VeiculoController;
import com.br.egaragens.entidades.Empresa;
import com.br.egaragens.entidades.Usuario;
import com.br.egaragens.entidades.Veiculo;
import com.br.egaragens.interfaces.IEntidade;
import com.br.egaragens.qrcode.IntentIntegrator;
import com.br.egaragens.util.Util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;

public class CadastroEntradaVeiculo extends Activity implements OnClickListener{
	/** Called when the activity is first created. */
	private EditText edtPlaca;
	private EmpresasController empresasController;
	private Empresa empresa;
	private Usuario usuario;

	private TableLayout tableRowNumerico;
	private TableLayout tableRowLetras;
	private String valor="";
	private String valorNumero="";
	private Button btn0;
	private Button btn1;
	private Button btn2;
	private Button btn3;
	private Button btn4;
	private Button btn5;
	private Button btn6;
	private Button btn7;
	private Button btn8;
	private Button btn9;

	private Button btnA;
	private Button btnB;
	private Button btnC;
	private Button btnD;
	private Button btnE;
	private Button btnF;
	private Button btnG;
	private Button btnH;
	private Button btnI;
	private Button btnJ;
	private Button btnK;
	private Button btnL;
	private Button btnM;
	private Button btnN;
	private Button btnO;
	private Button btnP;
	private Button btnQ;
	private Button btnR;
	private Button btnS;
	private Button btnT;
	private Button btnU;
	private Button btnV;
	private Button btnW;
	private Button btnX;
	private Button btnY;
	private Button btnZ;

	private Button backSpace;
	private VeiculoController veiculoController;
	private Veiculo veiculo;
	private List<Veiculo> veiculoBusca;
	private SimpleDateFormat dtForm = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cadastro_carro);
		edtPlaca = (EditText) findViewById(R.id.edtPlaca);
		tableRowNumerico =(TableLayout) findViewById(R.id.teclado_numerico);
		tableRowLetras=(TableLayout) findViewById(R.id.teclado_letras);
		estanciaButtons();
		empresasController = new EmpresasController(getBaseContext());
		empresa = (Empresa) empresasController.getAll().get(0);
		tableRowNumerico.setVisibility(View.GONE);
		veiculo = (Veiculo) getIntent().getSerializableExtra("veiculo");
		usuario = Util.usuario;
	}

	private void estanciaButtons() {
		veiculoController = new VeiculoController(getBaseContext());
		backSpace = (Button) findViewById(R.id.btnbackspace);
		backSpace.setOnClickListener(this);

		btn0 = (Button) findViewById(R.id.n0);
		btn0.setOnClickListener(this);

		btn1 = (Button) findViewById(R.id.n1);
		btn1.setOnClickListener(this);

		btn2 = (Button) findViewById(R.id.n2);
		btn2.setOnClickListener(this);

		btn3 = (Button) findViewById(R.id.n3);
		btn3.setOnClickListener(this);

		btn4 = (Button) findViewById(R.id.n4);
		btn4.setOnClickListener(this);

		btn5 = (Button) findViewById(R.id.n5);
		btn5.setOnClickListener(this);

		btn6 = (Button) findViewById(R.id.n6);
		btn6.setOnClickListener(this);

		btn7 = (Button) findViewById(R.id.n7);
		btn7.setOnClickListener(this);

		btn8 = (Button) findViewById(R.id.n8);
		btn8.setOnClickListener(this);

		btn9 = (Button) findViewById(R.id.n9);
		btn9.setOnClickListener(this);

		btnA = (Button) findViewById(R.id.A);
		btnA.setOnClickListener(this);

		btnB = (Button) findViewById(R.id.B);
		btnB.setOnClickListener(this);

		btnC = (Button) findViewById(R.id.C);
		btnC.setOnClickListener(this);

		btnD = (Button) findViewById(R.id.D);
		btnD.setOnClickListener(this);

		btnE = (Button) findViewById(R.id.E);
		btnE.setOnClickListener(this);

		btnF = (Button) findViewById(R.id.F);
		btnF.setOnClickListener(this);

		btnG = (Button) findViewById(R.id.G);
		btnG.setOnClickListener(this);

		btnH = (Button) findViewById(R.id.H);
		btnH.setOnClickListener(this);

		btnI = (Button) findViewById(R.id.I);
		btnI.setOnClickListener(this);

		btnJ = (Button) findViewById(R.id.J);
		btnJ.setOnClickListener(this);

		btnK = (Button) findViewById(R.id.K);
		btnK.setOnClickListener(this);

		btnL = (Button) findViewById(R.id.L);
		btnL.setOnClickListener(this);

		btnM = (Button) findViewById(R.id.M);
		btnM.setOnClickListener(this);

		btnN = (Button) findViewById(R.id.N);
		btnN.setOnClickListener(this);

		btnO = (Button) findViewById(R.id.O);
		btnO.setOnClickListener(this);

		btnP = (Button) findViewById(R.id.P);
		btnP.setOnClickListener(this);

		btnQ = (Button) findViewById(R.id.Q);
		btnQ.setOnClickListener(this);

		btnR = (Button) findViewById(R.id.R);
		btnR.setOnClickListener(this);

		btnS = (Button) findViewById(R.id.S);
		btnS.setOnClickListener(this);

		btnT = (Button) findViewById(R.id.T);
		btnT.setOnClickListener(this);

		btnU = (Button) findViewById(R.id.U);
		btnU.setOnClickListener(this);

		btnV = (Button) findViewById(R.id.V);
		btnV.setOnClickListener(this);

		btnW = (Button) findViewById(R.id.W);
		btnW.setOnClickListener(this);

		btnX = (Button) findViewById(R.id.X);
		btnX.setOnClickListener(this);

		btnY = (Button) findViewById(R.id.Y);
		btnY.setOnClickListener(this);

		btnZ = (Button) findViewById(R.id.Z);
		btnZ.setOnClickListener(this);



	}
	public void onClick(View v) {

		if(v.getId()==backSpace.getId()){
			vibrate(120);
			if(valor.length() > 0){
				valor=valor.substring(0,valor.length() -1);
				edtPlaca.setText(valor);
			}
			if(valor.length() < 3){
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				tableRowLetras.setVisibility(View.VISIBLE);
				tableRowNumerico.setVisibility(View.GONE);
			}
			if(valor.length() == 0){
				valor+="";
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				tableRowLetras.setVisibility(View.VISIBLE);
				tableRowNumerico.setVisibility(View.GONE);
			}

		}
		backSpace.setOnLongClickListener(new View.OnLongClickListener() {

			public boolean onLongClick(View v) {
				vibrate(120);
				valor="";
				edtPlaca.setText(valor);
				return false;
			}
		});

		if(tableRowNumerico.getVisibility() == View.VISIBLE){

			if(valor.length() > 3){
				valorNumero = valor.substring(4, valor.length()).replace("-", "").trim();

				if(v.getTag() != null && valorNumero.length() < 4 ){
					vibrate(120);
					valor+=v.getTag();
					edtPlaca.setText(valor);
					valorNumero = valor.substring(4, valor.length()).replace("-", "").trim();	
				}
			}
			if(valorNumero.length() == 4){
				IntentIntegrator integrator = new IntentIntegrator(this);
				integrator.initiateScan();
			}

		}
		if(tableRowLetras.getVisibility() == View.VISIBLE){

			if(v.getTag() != null){
				vibrate(120);
				valor+=v.getTag();
				edtPlaca.setText(valor);
			}

			if(valor.length() == 3){
				valor+="-";
				edtPlaca.setText(valor);
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				tableRowLetras.setVisibility(View.GONE);
				tableRowNumerico.setVisibility(View.VISIBLE);
			}
		}

		v.invalidate();

	}
	public void onActivityResult(int requestCode, int resultCode,Intent data){

		if(resultCode == RESULT_OK){
			String qrcode = data.getStringExtra("SCAN_RESULT");
			veiculoBusca =  veiculoController.getPeloQrcodeStatus(qrcode);
			
	
			if(validaQrCode(qrcode)){
				if(veiculoBusca.size() == 0){
					veiculo.setIdQrCode(qrcode);
					veiculo.setPlaca(edtPlaca.getText().toString());
					veiculo.setDtHoraEntrada(dtForm.format(new Date()));
					veiculo.setStatus(false);
					veiculoController.inserir(veiculo);
					finish();
					Intent intent = new Intent(this, FinalizaEntrada.class);
					intent.putExtra("veiculo", veiculo);
					startActivity(intent);
				}else{
					AlertDialog.Builder alBuilder = new AlertDialog.Builder(this);
					alBuilder.setTitle("Aten��o!");
					alBuilder.setMessage("J� existe um placa cadastrada com o QrCode importado que " +
							"ainda n�o foi fechado, favor realizar o fechamento antes de cadastrar outro veiculo!");
					alBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {

							irTelaFinalizar();
						}
					});
					alBuilder.show();
				}

			}else{

				AlertDialog.Builder alBuilder = new AlertDialog.Builder(this);
				alBuilder.setTitle("Aten��o!");
				alBuilder.setMessage("Este cart�o n�o � permitido para o USU�RIO. Use um cart�o com o n�mero entre " +usuario.getQtdCartoes().split(";")[0]+
						" � "+usuario.getQtdCartoes().split(";")[1]);
				alBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

					}
				});
				alBuilder.show();
			}
		}
		else{

			AlertDialog.Builder alBuilder = new AlertDialog.Builder(this);
			alBuilder.setTitle("Aten��o!");
			alBuilder.setMessage("Erro ao realizar a leitura do QrCode!");
			alBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {

				}
			});
			alBuilder.show();
		}
	}
	public void irTelaFinalizar(){
		finish();
		
	}
	public void onBackPressed(){
		finish();

	}
	private void vibrate(long tempo) {
		Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		vibrator.vibrate(tempo);
	}
	public boolean validaQrCode(String qrCode){
		try {
			if(qrCode.length() > 7){
				String[] valorCartao = Util.usuario.getQtdCartoes().toString().split(";");
				int inicio = Integer.parseInt(valorCartao[0]);
				int fim = Integer.parseInt(valorCartao[1]);
				int valorQrCode=Integer.parseInt(qrCode.toString().substring(6,qrCode.toString().length()));

				if(qrCode.length() > 6){

					if(qrCode.toString().substring(0, 6).equals(String.format("%06d", empresa.getEmpresaID()))){

						if(valorQrCode >= inicio && valorQrCode <=fim ){
							return true;
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	
		
		return false;

	}
}